/**
 * 编辑器相关的组合式函数
 * 提供编辑器状态管理、工具控制等功能
 */

import { ref, computed, watch } from 'vue'
import { useEditorStore } from '../stores/editor'

// 编辑器工具组合式函数
export function useEditorTools() {
  const editorStore = useEditorStore()
  const currentTool = ref('select')
  const toolOptions = ref({})

  const tools = [
    { id: 'select', name: '选择工具', icon: 'cursor', shortcut: 'V' },
    { id: 'move', name: '移动工具', icon: 'move', shortcut: 'M' },
    { id: 'rotate', name: '旋转工具', icon: 'rotate', shortcut: 'R' },
    { id: 'scale', name: '缩放工具', icon: 'resize', shortcut: 'S' },
    { id: 'text', name: '文本工具', icon: 'text', shortcut: 'T' },
    { id: 'shape', name: '形状工具', icon: 'shapes', shortcut: 'U' }
  ]

  const setTool = (toolId: string, options = {}) => {
    currentTool.value = toolId
    toolOptions.value = options
  }

  const getTool = (toolId: string) => {
    return tools.find(tool => tool.id === toolId)
  }

  const getCurrentTool = computed(() => getTool(currentTool.value))

  return {
    currentTool,
    toolOptions,
    tools,
    setTool,
    getTool,
    getCurrentTool
  }
}

// 编辑器视口组合式函数
export function useEditorViewport() {
  const editorStore = useEditorStore()
  
  const viewport = computed(() => editorStore.viewport)
  
  const zoomIn = (factor = 1.2) => {
    const newZoom = Math.min(5, viewport.value.zoom * factor)
    editorStore.viewport.zoom = newZoom
  }

  const zoomOut = (factor = 0.8) => {
    const newZoom = Math.max(0.1, viewport.value.zoom * factor)
    editorStore.viewport.zoom = newZoom
  }

  const zoomToFit = () => {
    // 计算适合所有图层的缩放级别
    const layers = editorStore.layers
    if (layers.length === 0) return

    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity

    layers.forEach(layer => {
      const { position } = layer
      minX = Math.min(minX, position.x - 50)
      minY = Math.min(minY, position.y - 50)
      maxX = Math.max(maxX, position.x + 50)
      maxY = Math.max(maxY, position.y + 50)
    })

    const width = maxX - minX
    const height = maxY - minY
    const viewportWidth = viewport.value.width
    const viewportHeight = viewport.value.height

    const scaleX = viewportWidth / width
    const scaleY = viewportHeight / height
    const scale = Math.min(scaleX, scaleY) * 0.8 // 留一些边距

    editorStore.viewport.zoom = Math.max(0.1, Math.min(5, scale))
    
    // 居中视图
    const centerX = (minX + maxX) / 2
    const centerY = (minY + maxY) / 2
    editorStore.viewport.panX = viewportWidth / 2 - centerX * editorStore.viewport.zoom
    editorStore.viewport.panY = viewportHeight / 2 - centerY * editorStore.viewport.zoom
  }

  const resetView = () => {
    editorStore.viewport.zoom = 1
    editorStore.viewport.panX = 0
    editorStore.viewport.panY = 0
  }

  const panTo = (x: number, y: number) => {
    editorStore.viewport.panX = x
    editorStore.viewport.panY = y
  }

  return {
    viewport,
    zoomIn,
    zoomOut,
    zoomToFit,
    resetView,
    panTo
  }
}

// 编辑器选择组合式函数
export function useEditorSelection() {
  const editorStore = useEditorStore()
  
  const selection = computed(() => editorStore.selection)
  const selectedLayers = computed(() => 
    editorStore.layers.filter(layer => 
      selection.value.selectedLayers.includes(layer.id)
    )
  )
  const selectedTracks = computed(() =>
    editorStore.tracks.filter(track =>
      selection.value.selectedTracks.includes(track.id)
    )
  )

  const selectLayer = (layerId: string, multiSelect = false) => {
    editorStore.selectLayer(layerId, multiSelect)
  }

  const selectTrack = (trackId: string, multiSelect = false) => {
    editorStore.selectTrack(trackId, multiSelect)
  }

  const selectKeyframe = (keyframeId: string, multiSelect = false) => {
    editorStore.selectKeyframe(keyframeId, multiSelect)
  }

  const clearSelection = () => {
    editorStore.clearSelection()
  }

  const selectAll = () => {
    const allLayerIds = editorStore.layers.map(layer => layer.id)
    editorStore.selection.selectedLayers = allLayerIds
  }

  const deleteSelected = () => {
    // 删除选中的图层
    selection.value.selectedLayers.forEach(layerId => {
      editorStore.removeLayer(layerId)
    })
    
    // 删除选中的轨道
    selection.value.selectedTracks.forEach(trackId => {
      editorStore.removeTrack(trackId)
    })
    
    clearSelection()
  }

  const duplicateSelected = () => {
    const duplicatedLayers: any[] = []
    
    // 复制选中的图层
    selectedLayers.value.forEach(layer => {
      const newLayer = editorStore.addLayer({
        ...layer,
        name: `${layer.name} 副本`,
        position: {
          x: layer.position.x + 20,
          y: layer.position.y + 20
        }
      })
      duplicatedLayers.push(newLayer)
    })
    
    // 选择复制的图层
    clearSelection()
    duplicatedLayers.forEach(layer => selectLayer(layer.id, true))
  }

  return {
    selection,
    selectedLayers,
    selectedTracks,
    selectLayer,
    selectTrack,
    selectKeyframe,
    clearSelection,
    selectAll,
    deleteSelected,
    duplicateSelected
  }
}

// 编辑器历史记录组合式函数
export function useEditorHistory() {
  const editorStore = useEditorStore()
  
  const history = computed(() => editorStore.history)
  const canUndo = computed(() => history.value.currentIndex > 0)
  const canRedo = computed(() => history.value.currentIndex < history.value.states.length - 1)

  const undo = () => {
    if (canUndo.value) {
      editorStore.undo()
    }
  }

  const redo = () => {
    if (canRedo.value) {
      editorStore.redo()
    }
  }

  const saveState = (description?: string) => {
    editorStore.saveState(description)
  }

  const clearHistory = () => {
    editorStore.clearHistory()
  }

  return {
    history,
    canUndo,
    canRedo,
    undo,
    redo,
    saveState,
    clearHistory
  }
}

// 编辑器快捷键组合式函数
export function useEditorShortcuts() {
  const { undo, redo } = useEditorHistory()
  const { selectAll, deleteSelected, duplicateSelected } = useEditorSelection()
  const { setTool } = useEditorTools()

  const shortcuts = {
    // 编辑操作
    'ctrl+z': undo,
    'cmd+z': undo,
    'ctrl+y': redo,
    'cmd+shift+z': redo,
    'ctrl+a': selectAll,
    'cmd+a': selectAll,
    'delete': deleteSelected,
    'backspace': deleteSelected,
    'ctrl+d': duplicateSelected,
    'cmd+d': duplicateSelected,
    
    // 工具切换
    'v': () => setTool('select'),
    'm': () => setTool('move'),
    'r': () => setTool('rotate'),
    's': () => setTool('scale'),
    't': () => setTool('text'),
    'u': () => setTool('shape')
  }

  const handleKeyDown = (event: KeyboardEvent) => {
    const key = event.key.toLowerCase()
    const ctrl = event.ctrlKey || event.metaKey
    const shift = event.shiftKey
    
    let shortcut = ''
    if (ctrl) shortcut += 'ctrl+'
    if (shift) shortcut += 'shift+'
    shortcut += key

    // 也检查 cmd 版本（macOS）
    const cmdShortcut = shortcut.replace('ctrl+', 'cmd+')
    
    const handler = shortcuts[shortcut] || shortcuts[cmdShortcut]
    if (handler) {
      event.preventDefault()
      handler()
    }
  }

  return {
    shortcuts,
    handleKeyDown
  }
}
